#ifndef _MAIN_H
#define _MAIN_H
#include<iostream>
#include<string>
#include<pthread.h>
#include<stdlib.h>
#include <sys/socket.h>
#include<netdb.h>
#include<sys/stat.h>
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include"headFile/sock.h"
#include"headFile/a_connect.h"
using namespace std;
#endif
void head_http_request(int fd){
    int n;
    a_connect ac(fd);
    while((n = ac.get_request_row()) != 0){
        //获取请求url类型
        ac.get_url_type();
        //获取请求头
        ac.get_request_head();
        //1.判断url类型 逻辑or获取静态资源
        if(ac.url_type == 'S'){
            cout<<"获取静态资源"<<endl;
            char path[100] = "../html_file/";
            strcat(path,ac.url);
            //查找静态资源是否存在
            int static_fd = open(path,O_RDONLY,0);
            if(static_fd == -1){
                static_fd = open("../html_file/error.html",O_RDONLY,0);
                ac.respose(static_fd,404,"Not Found");
                close(static_fd);
            }
            else{
                ac.respose(static_fd,200,"OK");
                close(static_fd);
            }
        }else if(ac.url_type == 'L'){
            cout<<"逻辑处理"<<endl;
            //处理登陆
            if(strstr(ac.url,"login")!=NULL){
                int static_fd = open("../html_file/main.html",O_RDONLY,0);
                ac.respose(static_fd,200,"OK");
                close(static_fd);
            }else{
                int static_fd = open("../html_file/error.html",O_RDONLY,0);
                ac.respose(static_fd,404,"Not Found");
                close(static_fd);
            }
        }else{
            cout<<"url格式错误"<<endl;
            int static_fd = open("../html_file/error.html",O_RDONLY,0);
            ac.respose(static_fd,404,"Not Found");
            close(static_fd);
        }
    }

    
}
void* head_client_thread(void *arg){
    int c_fd = *((int*)arg);
    cout<<"子线程:"<<c_fd<<endl;
    pthread_detach(pthread_self());
    //处理客户端需求
    head_http_request(c_fd);
    close(c_fd);
    return NULL;
}
int main(int argc,char **argv){
    struct sockaddr *addr;//用于存储客户端的地址信息
    socklen_t len;//用于存储客户端的地址信息长度
    char c_hostname[Max],c_port[Max];//解析出客户端的的ip和端口，存储
    //cout<<argv[1]<<endl; //输出服务端端口
    int fd = open_listenfd(argv[1]);//服务端获取套接子
    pthread_t tid;
    int c_fd ,copy;
    while(1){
        cout<<"等待客户端连接..........."<<endl;
        c_fd = accept(fd,addr,&len);
        copy = c_fd;
        cout<<c_fd<<endl;
        if(c_fd<0){
            cout<<"accept fail!"<<endl;
            break;
        }
        getnameinfo(addr,len,c_hostname,Max,c_port,Max,0);
        cout<<"客户端ip:"<<c_hostname<<endl;
        cout<<"客户端port:"<<c_port<<endl;
        cout<<"套接描述符:"<<c_fd<<endl;
        pthread_create(&tid,NULL,head_client_thread,&copy);
    }
}